package com.lap.auth.filter;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import lombok.Data;

@Data
public class Security {
  private List<Ignore> tokenList;
  private List<Ignore> authorizationList;

  public Security() {
    this.tokenList =
        List.of(
            new Ignore("/api/v1/authentication/signIn", "post"),
            new Ignore("/api/v1/authentication/refresh", "post"));
  }

  /**
   * 是否忽略token
   *
   * @param uri 请求uri
   * @param method 请求方法
   * @return 是否忽略，true-忽略,false-不忽略
   */
  public boolean ignoreToken(String uri, String method) {
    return contain(tokenList, uri, method);
  }

  /**
   * 忽略权限的请求，必然包含忽略token的,不然鉴权的时候,忽略token必然没有权限
   *
   * @param uri 请求uri
   * @param method 请求方法
   * @return 是否忽略，true-忽略,false-不忽略
   */
  public boolean ignoreAuthor(String uri, String method) {
    return contain(
        Stream.concat(
                Optional.ofNullable(tokenList).orElseGet(ArrayList::new).stream(),
                Optional.ofNullable(authorizationList).orElseGet(ArrayList::new).stream())
            .toList(),
        uri,
        method);
  }

  private boolean contain(List<Ignore> dataList, String uri, String method) {
    return Optional.ofNullable(dataList).orElseGet(ArrayList::new).stream()
        .anyMatch(u -> u.uri.equalsIgnoreCase(uri) && u.method.equalsIgnoreCase(method));
  }

  public record Ignore(String uri, String method) {

    @Override
    public String toString() {
      return "Ignore{" + "uri='" + uri + '\'' + ", method='" + method + '\'' + '}';
    }
  }
}
